<script setup lang="ts">
import { onMounted, ref, reactive, onBeforeUnmount, shallowRef, watch } from 'vue';
import { Global } from "../Global";
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

const props = defineProps(['modelValue']);
const emit = defineEmits(['update:modelValue']);
const content = ref("");

watch(content , (newValue:any)=>{
  emit("update:modelValue", newValue);
});

watch(()=>props.modelValue , (newValue:any)=>{
  content.value = newValue? newValue:"";
});

const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: `${Global.ServerUrl}/UploadFormFile/Upload`,
      headers: {
        Authorization: Global.UserInfo.Token
      },
    }
  }

}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  console.log("DocEditor onBeforeUnmount");
  editorRef.value?.destroy();
})

const handleCreated = (editor: any) => {
  console.log("DocEditor handleCreated");
  if(props.modelValue)
  {
    content.value = props.modelValue;
  }
  editorRef.value = editor // 记录 editor 实例，重要！
}

</script>

<template>
  <div style="border: 1px solid #ccc;height: 100%;width: 100%;">
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" mode="default" />
    <Editor style="height: 500px; overflow-y: hidden;" v-model="content" :defaultConfig="editorConfig"
      mode="default" @onCreated="handleCreated" />
  </div>
</template>

<style scoped lang="scss"></style>